package com.zx.template.task;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 需要加延时的业务对象
 */
@Getter
@Setter
@ToString
@Slf4j
@Builder
public class DelayedMessage implements Delayed {

    /**
     * 其他字段任意
     */
    private String msg;
    /**
     * 延迟多少秒(发消息推送）
     */
    private Long delaySeconds;

    /**
     * 这里 调用queue.poll.都会被调用
     *
     * @param unit 时间单位
     * @return 这里不好打印，因为会有很多条
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.delaySeconds - System.currentTimeMillis() / 1000, TimeUnit.SECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        DelayedMessage other = (DelayedMessage) o;
        long diff = this.delaySeconds - other.delaySeconds;
        if (diff <= 0) {
            return -1;
        } else {
            return 1;
        }
    }
}
